package com.demo.cotroller;


import com.demo.domain.User;
import com.demo.domain.Users;
import com.demo.repository.UserRepository;
import com.demo.util.CheckUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Optional;

/**
 * Created by wangzhanjin on 2018/5/31.
 * RestController=ResponseBody+Controller
 */
@RestController
@RequestMapping("/user")
public class UserController {


    @Autowired
    private UserRepository repository;


    @GetMapping("/")
    public List<User> getAll() {
//        throw new RuntimeException("测试使用");
        List<User> all = repository.findAll();
        return all;
    }

    @GetMapping(value = "/stream/all", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public List<User> streamGetAll() {
        return repository.findAll();
    }

    /**
     * 新增数据
     *
     * @param users
     * @return
     */
    @PostMapping("/")
    public User createUser(@RequestBody Users users) {
        //spring data jpa里面，新增和修改都是save，有id是修改,id为空是新增
        //根据实际情况是否置空id
//        BeanUtils.copyProperties(users,user);
        return repository.save(null);
    }

    @RequestMapping("/str")
    public String createUser(@RequestParam String str) {
        return str + "路过";
    }



    /**
     * 根据id删除用户
     * 存在的时候返回200，不存在返回404
     *
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteUser(@PathVariable("id") String id) {
        //deleteById返回是voidMono，也就是没有返回值，不能判断数据是否存在
//        return repository.findById(id)
//                //当你要操作数据，并返回一个Mono，这时候使用flatMap
//                //如果不操作数据，只是转换数据，使用map
//                .flatMap(user -> repository.delete(user).then(new ResponseEntity<Void>(HttpStatus.OK)))
//                .defaultIfEmpty(new ResponseEntity<>(HttpStatus.NOT_FOUND));
        return null;
    }

    /**
     * 更新数据
     * @param id
     * @param user
     * @return
     */
    @PutMapping("/{id}")
    public Optional<User> updateUser(@PathVariable("id") String id,
                                                 @Valid @RequestBody User user) {
        CheckUtil.checkName(user.getName());
        Optional<User> byId = this.repository.findById(id);
        return byId;
                //flatMap操作数据
//                .flatMap(u -> {
//                    u.setAge(user.getAge());
//                    u.setName(user.getName());
//                    //save方法后返回mono
//                    return repository.save(u);
//                })
//                //转换数据
//                .map(u -> new ResponseEntity<User>(u,HttpStatus.OK))
//                .defaultIfEmpty(new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }


    @GetMapping("/{id}")
    public User findUserById(@PathVariable("id") String id) {
//        this.repository.findById(id).ifPresent(user -> new ResponseEntity<User>(user,HttpStatus.OK));
        return repository.findById(id).get();
    }


    /**
     * 根据年龄查询用户
     * @param start
     * @param end
     * @return
     */
    @GetMapping("/age/{start}/{end}")
    public List<User> findByAge(@PathVariable("start") int start, @PathVariable("end") int end) {
        return repository.findByAgeBetween(start, end);
    }


    @GetMapping(value = "/stream/age/{start}/{end}", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public List<User> streamFindByAge(@PathVariable("start") int start, @PathVariable("end") int end) {
        return repository.findByAgeBetween(start, end);
    }

    /**
     * 得到20~29的用户
     * @return
     */
    @GetMapping("/old")
    public List<User> oldUser() {
        return repository.oldUser();
    }


    @GetMapping(value = "/stream/old}", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public List<User> streamOldUser() {
        return repository.oldUser();
    }

}















